<?php

namespace App\Admin\Controllers;

use App\Models\Engineering;
use App\Models\ZiliaoContent;
use App\Models\ZiliaoCategory;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Card;
use Illuminate\Support\Facades\DB;
use App\Admin\Actions\Grid\ZiliaoRevoke;

class ZiliaoContentController extends AdminController
{
    protected $title = '资料提报';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ZiliaoContent(), function (Grid $grid) {
            $grid->disableViewButton();
            $grid->perPages([10, 20, 30, 40, 50,100,200,300,400,500]);


            $Adminid  = Admin::user()->id;
            $grid->model()->where('process', 'like','%'.$Adminid.'%')->ORwhere('uploader', 'like','%'.$Adminid.'%')->where('status','<',4);


//            if (Admin::user()->can('inspector')) {
//                $Adminid  = Admin::user()->id;
//                $grid->model()->where('uploader', $Adminid)->where('status', 1);
//            }
//
//            if (Admin::user()->can('project_manager')) {
//                $Adminid  = Admin::user()->id;
//                $manager = DB::table('engineering')->where('manager','like','%'.$Adminid.'%')->where('deleted_at',null)->pluck('manager');
//                foreach ($manager as $key => $value){
//                    $clean_string = str_replace(["[", "]", "(", ")"], "", $value);
//                    $clean_string = explode(',',$clean_string);
//
//                    foreach ($clean_string as $k => $v){
//                        $v = str_replace(["'", '"'], '', $v);
//                        $role_id = DB::table('admin_role_users')->where('user_id',$v)->value('role_id');
//                        if($role_id == 3){
//                            $grid->model()->where('uploader', $v)->where('status', 2);
//                        }
//                    }
//                }
//            }

            $ziliao_categories = DB::table('ziliao_categories')->get()->map(function ($value) {return (array)$value;})->toArray();
            $is_creat = false;
            foreach ($ziliao_categories as $key => $value){
                $process_array = json_decode($value['process'],true);
                foreach ($process_array as $k => $v){
                    if($v['type'] == 1){
                        if($v['role'] == Admin::user()->roles[0]['slug']){
                            $is_creat = true;
                        }
                    }
                }
            }

            if(!$is_creat){
                $grid->disableCreateButton();
            }

            $is_Revoke = false;

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $Adminid  = Admin::user()->id;
                $process = $actions->row->process;
                if(!empty($process) && $actions->row->uploader == $Adminid && $actions->row->status>=2){
                    $actions->disableEdit();
                    $actions->append(new ZiliaoRevoke());
                    $actions->disableDelete();
                }

            });


            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('categories_id')->display(function ($categories_id) {
                return DB::table('ziliao_categories')->where('id',$categories_id)->value('title');
            });
            $grid->column('engineering');

//            $grid->column('content');
//            $grid->column('attachment');


            $grid->column('status_info','流程详情')
                ->display('流程详情') // 设置按钮名称
                ->modal(function ($modal) {

                    $status_info = json_decode($this->status_info,true);
                    $status_info_view = "";
                    foreach ($status_info as $key => $value){
//                        var_dump($value['type']);
                        $username = DB::table('admin_users')->where('id',$value['process'])->value('username');
                        if($value['status'] == 0){
                            $status = "<span style='color:red'>尚未通过</span>";
                        }elseif($value['status'] == 1){
                            $status = "<span style='color:green'>报审通过</span>";
                        }elseif($value['status'] == 2){
                            $status = "<span style='color:darkred'>驳回</span>";
                        }
                        if($value['method'] == 1){
                            $method = "<span style='color:darkgoldenrod'>串行</span>";
                        }else{
                            $method = "<span style='color:#a71d5d'>并行</span>";
                        }
                        $status_info_view .= '处理人员:'."<span style='color:blue'>$username</span>".'--报审状态:'.$status.'--报审时间:'.$value['time'].'--报审方式:'.$method.'<br><br>';
                    }
                    $card = new Card(null, $status_info_view);
                    return "<div style='padding:10px 10px 0'>$card</div>";
                });


            $grid->column('created_at');

            $grid->column('uploader','上报者')->display(function ($uploader) {
                return DB::table('admin_users')->where('id',$uploader)->value('username');
            });

//            $grid->column('updated_at')->sortable();

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ZiliaoContent(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('categories_id');
            $show->field('engineering');
            $show->field('content');
            $show->field('attachment');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ZiliaoContent(), function (Form $form) {
            $form->display('id');
            $form->text('title');

            if(empty($form->getKey())){
                $form->select('categories_id','资料分类')->options(function ($id) {

                    $qualified_id = [];
                    $res = DB::table('ziliao_categories')->where('title','<>','')->get()->map(function ($value) {return (array)$value;})->toArray();
                    foreach ($res as $key => $value){
                        $process = json_decode($value['process'],true);
                        if($process[0]['role'] == Admin::user()->roles[0]['slug']){
                            $qualified_id[] = $value['id'];
                        }
                    }
                    return ZiliaoCategory::where('title','<>','')->whereIn('id',$qualified_id)->pluck('title', 'title');
                });
            }else{
                $form->text('categories_id','资料分类');
            }


            $form->select('engineering','所属工程')->options(function ($id) {
                return Engineering::where('engineering_name','<>','')->pluck('engineering_name', 'engineering_name');
            });

//            $form->select('engineering','所属工程')->options(function ($id) {
//                $Adminid  = Admin::user()->id;
//                if($Adminid != 1 && Admin::user()->whole != 0){
//                    $engineering_name = DB::table('engineering')->where('manager','like','%'.$Adminid.'%')->where('deleted_at',null)->pluck('engineering_name');
//                }else{
//                    $engineering_name = DB::table('engineering')->where('deleted_at',null)->pluck('engineering_name');
//                }
//                $arr = [];
//                foreach ($engineering_name as $key => $value){
//                    $arr["$value"] = $value;
//                }
//                return $arr;
//            })->width(5);


            $form->editor('content');
            $form->file('attachment','送审附件')->accept('xlsx,xls,doc,docx,pdf')->downloadable()->autoUpload();

            $form->file('attachment','归档附件')->accept('xlsx,xls,doc,docx,pdf')->downloadable()->autoUpload();

            $form->multipleImage('image','图片')->saving(function ($paths) {
                return json_encode($paths,JSON_UNESCAPED_UNICODE);
            })->downloadable()->autoUpload();

            $form->hidden('status');

            if(empty($form->model()->status) || $form->model()->status == 1){
                $form->radio('status','审核')->options(['1' => '未送审', '2'=> '提交审核'])->default('1');
            }elseif($form->model()->status >= 2 && trim($form->model()->process, ',') != array_slice(json_decode($form->model()->status_info,true),-1)[0]['process']){
                $form->radio('status','审核')->options(['0' => '驳回', '3'=> '通过'])->required();
            }elseif(trim($form->model()->process, ',') == array_slice(json_decode($form->model()->status_info,true),-1)[0]['process']){
                $form->radio('status','审核')->options(['4' => '搁置', '5'=> '归档'])->required();
            }

//dd(array_slice(json_decode($form->model()->status_info,true),-1)[0]['process']);
//            if (Admin::user()->can('project_manager')) {
//                $form->radio('status','审核')->options(['1' => '驳回', '2'=> '正在审核', '3'=> '审核通过'])->default('1');
//            }


            $form->hidden('uploader');
            $form->hidden('process');
            $form->hidden('step');
            $form->hidden('role');
            $form->hidden('status_info');

            $form->display('created_at');
            $form->display('updated_at');


            $form->saving(function (Form $form) {
                $Adminid  = Admin::user()->id;

                if($form->isCreating()){
                    $form->uploader = $Adminid;
                }

                if(empty($form->model()->step) || $form->model()->step == 0){
                    $step = 2;
                }else{
                    $step = $form->model()->step + 1;
                }

                if($form->status == 1){
                    $form->process = $Adminid;
                    $process = DB::table('ziliao_categories')->where('title',$form->categories_id)->value('process');
                    $process_array = json_decode($process,true);

                    $status_info = [];
                    foreach ($process_array as $key => $value){
                        $status_info[$key]['type'] = $value['type'];
                        $status_info[$key]['method'] = $value['method'];
                        $status_info[$key]['role'] = $value['role'];
                        $status_info[$key]['step'] = $value['step'];

                        $manager = DB::table('engineering')->where('engineering_name',$form->engineering)->where('deleted_at',null)->value('manager');
                        $clean_string = explode(',',str_replace(["[", "]", "(", ")"], "", $manager));
                        foreach ($clean_string as $k => $v){
                            $user_id = str_replace(["'", '"'], '', $v);
                            $role_id = DB::table('admin_role_users')->where('user_id',$user_id)->value('role_id');
                            $slug = DB::table('admin_roles')->where('id',$role_id)->value('slug');
                            if($slug == $process_array[$key]['role']){
                                $status_info[$key]['process'] = $user_id;
                            }
                        }
                        $status_info[$key]['status'] = 0;
                        $status_info[$key]['time'] = "";
                    }

                    $status_info[0]['status'] = 0;
                    $status_info[0]['time'] = Carbon::now('Asia/Shanghai')->format('Y-m-d H:i:s');
                    $form->status_info = json_encode($status_info,JSON_UNESCAPED_UNICODE);
                }

                if($form->status == 2){

                    $process = DB::table('ziliao_categories')->where('title',$form->categories_id)->value('process');
                    $process_array = json_decode($process,true);

                    $status_info = [];
                    foreach ($process_array as $key => $value){
                        $status_info[$key]['type'] = $value['type'];
                        $status_info[$key]['method'] = $value['method'];
                        $status_info[$key]['role'] = $value['role'];
                        $status_info[$key]['step'] = $value['step'];

                        $manager = DB::table('engineering')->where('engineering_name',$form->engineering)->where('deleted_at',null)->value('manager');
                        $clean_string = explode(',',str_replace(["[", "]", "(", ")"], "", $manager));
                        foreach ($clean_string as $k => $v){
                            $user_id = str_replace(["'", '"'], '', $v);
                            $role_id = DB::table('admin_role_users')->where('user_id',$user_id)->value('role_id');
                            $slug = DB::table('admin_roles')->where('id',$role_id)->value('slug');
                                if($slug == $process_array[$key]['role']){
                                    $status_info[$key]['process'] = $user_id;
                                }
                        }
                        $status_info[$key]['status'] = 0;
                        $status_info[$key]['time'] = "";
                    }

                    $status_info[0]['status'] = 1;
                    $status_info[0]['time'] = Carbon::now('Asia/Shanghai')->format('Y-m-d H:i:s');
                    $form->status_info = json_encode($status_info,JSON_UNESCAPED_UNICODE);

                    $process = "";
                    foreach ($status_info as $key => $value){
                        if($value['step'] == $step){
                            $process .= $value['process'].',';
                        }
                    }
                    $form->process = $process;
                    $form->step = 2;
                }

                if($form->status == 3){
                    $status_info = $form->model()->status_info;
                    $status_info_array = json_decode($status_info,true);
                    foreach ($status_info_array as $key => $value){
                        if($value['step'] == $form->step && $value['process'] == $Adminid){
                            $status_info_array[$key]['status'] = 1;
                            $status_info_array[$key]['time'] = Carbon::now()->format('Y-m-d H:i:s');
                        }
                    }

                    $form->status_info = json_encode($status_info_array,JSON_UNESCAPED_UNICODE);

                    $process_end = 0;
                    foreach ($status_info_array as $key => $value){
                        if($value['step'] == $form->step){
                            if($value['status'] == 0){
                                $process_end = 1;
                            }
                        }
                    }
//                    dd($process_end);
                    if($process_end == 0){
                        $step = $form->model()->step + 1;
                        $process = "";
                        foreach ($status_info_array as $key => $value){
                            if($value['step'] == $step){
                                $process .= $value['process'].',';
                            }
                        }
                        $form->process = $process;
                        $form->step = $step;
                    }

                }

                if($form->status == 5){
                    $status_info = $form->model()->status_info;
                    $status_info_array = json_decode($status_info,true);
                    foreach ($status_info_array as $key => $value){
                        if($value['step'] == $form->step && $value['process'] == $Adminid){
                            $status_info_array[$key]['status'] = 1;
                            $status_info_array[$key]['time'] = Carbon::now()->format('Y-m-d H:i:s');
                        }
                    }

                    $form->status_info = json_encode($status_info_array,JSON_UNESCAPED_UNICODE);
                }

                if($form->status == 4){
                    $form->status = 3;
                }

                if($form->status == 0 && !empty($form->status)){

                    $status_info = $form->model()->status_info;
                    $status_info_array = json_decode($status_info,true);
                    foreach ($status_info_array as $key => $value){
                        if($value['step'] == $form->step && $value['process'] == $Adminid){
                            $status_info_array[$key]['status'] = 2;
                            $status_info_array[$key]['time'] = Carbon::now()->format('Y-m-d H:i:s');
                        }
                    }

                    $form->status_info = json_encode($status_info_array,JSON_UNESCAPED_UNICODE);


                    $process = DB::table('ziliao_categories')->where('title',$form->categories_id)->value('process');
                    $process_array = json_decode($process,true);

                    $form->role = $process_array[0]['role'];
                    $form->process = $form->model()->uploader;
                    $form->step = 0;
                    $form->status = 1;

                }

            });

        });



    }


}
